package Server.ServerCore.Service.Logic;

import com.alibaba.fastjson.JSON;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;


/***
 * json handle
 */
public  class AdapterBuildPack{
    /**
     * 将javabean转换为json串，发送到客户端
     * if arg1<0,please get this method
     * @param arg1  must be arg1<0
     * 获取构建的数据包
     * @return ChannelBuffer
     */
    public ChannelBuffer getJsonData(int arg1) {
        return this.getJsonData(arg1, 0x0);
    }
    /**
     * 获取构建的数据包
     * @param arg1 协议类型1
     * @param arg2 协议类型2
     * @return  ChannelBuffer
     */
    public ChannelBuffer getJsonData(int arg1, int arg2) {
        ChannelBuffer buffer= ChannelBuffers.dynamicBuffer(0x80);
        if(arg1> 0x0){
            return buildBufferData(arg1,arg2,buffer);
        }else {
            return buildBufferData(arg1,buffer);
        }
    }




    /**
     *
     * @param arg1 协议类型1
     * @param arg2 协议类型2
     * @param buffer
     * @return   ChannelBuffer
     */
    private  ChannelBuffer buildBufferData(int arg1, int arg2,ChannelBuffer buffer) {
        if (buffer==null){
            buffer=ChannelBuffers.dynamicBuffer(0x80);
        }
        buffer.writeShort(Short.MIN_VALUE);//占2字节
        buffer.writeByte(arg1);//1字节
        buffer.writeByte(arg2);//1字节
        buffer.writeBytes(JSON.toJSONString(this).getBytes());
        buffer.setShort(0,buffer.writerIndex()-0x2);
        return buffer;
    }

    /**
     * @param arg1 协议类型1  协议类型arg1<0
     * @return   ChannelBuffer
     */
    private  ChannelBuffer buildBufferData(int arg1,ChannelBuffer buffer) {
        if (buffer==null){
            buffer=ChannelBuffers.dynamicBuffer(0x80);
        }
        buffer.writeShort(Short.MIN_VALUE);//占2字节
        buffer.writeByte(arg1);
        buffer.writeBytes(JSON.toJSONString(this).getBytes());
        buffer.setShort(0,buffer.writerIndex()-0x2);
        return buffer;
    }




}
